﻿using D.Wx.Consts;
using D.Wx.Dtos;
using D.Wx.Entities;
using D.Wx.Filter;
using D.Wx.IRepository;
using D.Wx.NLogsUtil;
using D.Wx.Utils;
using Flurl;
using Flurl.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Crypto;
using System;
using System.Security.Principal;

namespace D.Wx
{
    /// <summary>
    /// 供应商
    /// </summary>
    [Route("api/sysPlatform")]
    [ApiController]
    public class SysPlatformController : ControllerBase
    {
        private readonly INLogService _logger;
        private readonly ISysPlatformRepository _sysPlatformRepository;

        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="sysPlatformRepository"></param>
        public SysPlatformController(ISysPlatformRepository sysPlatformRepository, INLogService logger)
        {
            _sysPlatformRepository = sysPlatformRepository;
            _logger = logger;
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns> 
        [HttpGet("queryPage"), TypeFilter(typeof(ActionFilter))]
        public async Task<ApiResult<PageModel<SysPlatformEntityOutput>>> QueryPage([FromQuery] SysPlatformEntityQuery query)
        {
            return new ApiResult<PageModel<SysPlatformEntityOutput>>()
            {
                Data = await _sysPlatformRepository.QueryPage(query)
            };
        }


        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns> 
        [HttpGet("getList"), TypeFilter(typeof(ActionFilter))]
        public async Task<ApiResult<List<SysPlatformEntity>>> GetList()
        {
            return new ApiResult<List<SysPlatformEntity>>()
            {
                Data = await _sysPlatformRepository.GetList()
            };
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost("add"), TypeFilter(typeof(ActionFilter))]
        public async Task<ApiResult<string>> Add([FromBody] SysPlatformEntity entity)
        {
            // 判断UUid是否存在
            var exists = await _sysPlatformRepository.Exists(entity.UUid);
            if (exists)
            {
                return new ApiResult<string>() { Success = true, StatusCode = StatusCodeEnum.Error, Msg = "UUID已重复" };
            }
            // 获取Token
            var token = await GetWxToken();
            if (string.IsNullOrEmpty(token))
            {
                return new ApiResult<string>() { Success = true, StatusCode = StatusCodeEnum.Error, Msg = "微信AccessToken获取失败" };
            }
            // 生成二维码
            var ticket = await GetTicket(token, entity.UUid);
            if (ticket == null)
            {
                return new ApiResult<string>() { Success = true, StatusCode = StatusCodeEnum.Error, Msg = "微信Ticket获取失败" };
            }

            var qrCodeImg = await GetBase64ImgStr(ticket.ticket);
            if (qrCodeImg == null)
            {
                return new ApiResult<string>() { Success = true, StatusCode = StatusCodeEnum.Error, Msg = "微信Base64二维码获取失败" };
            }

            // 生成推广连接
            entity.LinkUrl = CodeUtils.GenerateCode(6);
            entity.QrCode = qrCodeImg;
            entity.Token = token;
            entity.Ticket = ticket.ticket;
            entity.TicketExpireSeconds = ticket.expire_seconds;
            entity.TicketUrl = ticket.url;

            var dwz = new SysDwzEntity()
            {
                EncrypCodeParams = entity.LinkUrl,
                SysPlatformId = entity.Id,
            };

            var res = await _sysPlatformRepository.Add(entity, dwz);
            if (res > 0)
            {
                return new ApiResult<string>() { Success = true, StatusCode = StatusCodeEnum.OK, Msg = "添加成功" };
            }
            return new ApiResult<string>() { Success = true, StatusCode = StatusCodeEnum.Error, Msg = "添加失败" };
        }

        /// <summary>
        /// 获取Base64Img
        /// </summary>
        /// <param name="ticket"></param>
        /// <returns></returns>
        private async Task<string> GetBase64ImgStr(string ticket)
        {
            try
            {
                var res = await "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket"
                         .SetQueryParams(new
                         {
                             ticket = ticket
                         })
                          .GetBytesAsync();

                return Convert.ToBase64String(res);
            }
            catch (Exception ex)
            {
                var error = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}>>>>获取微信AccessToken异常>>>>>{ex.Message}";
                _logger.Error(error);
                Console.WriteLine(error);
                return null;
            }
        }

        /// <summary>
        /// 获取Ticket
        /// </summary>
        /// <param name="token"></param>
        /// <param name="uuid"></param>
        /// <returns></returns>
        private async Task<TicketResponse> GetTicket(string token, string uuid)
        {
            try
            {
                var res = await "https://api.weixin.qq.com/cgi-bin/qrcode/create"
                  .SetQueryParams(new
                  {
                      access_token = token
                  })
                     .PostJsonAsync(new
                     {
                         action_name = "QR_LIMIT_STR_SCENE", // 二维码类型，QR_SCENE为临时的整型参数值，QR_STR_SCENE为临时的字符串参数值，QR_LIMIT_SCENE为永久的整型参数值，QR_LIMIT_STR_SCENE为永久的字符串参数值
                         action_info = new // 二维码详细信息
                         {
                             scene = new
                             {
                                 scene_str = uuid // 场景值ID（字符串形式的ID），字符串类型，长度限制为1到64
                             }
                         }
                     }).ReceiveJson<TicketResponse>();

                return res;
            }
            catch (Exception ex)
            {
                var error = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}>>>>获取微信AccessToken异常>>>>>{ex.Message}";
                _logger.Error(error);
                Console.WriteLine(error);
                return null;
            }
        }
        /// <summary>
        /// 获取微信AccessToken
        /// </summary>
        private async Task<string> GetWxToken()
        {
            try
            {
                // 初始化全局微信公众号的Token
                var accesstoken = await "https://api.weixin.qq.com/cgi-bin/token"
                                  .SetQueryParams(new
                                  {
                                      grant_type = "client_credential",
                                      appid = WeixinSetting.Appid,
                                      secret = WeixinSetting.Appsecret
                                  })
                               .GetJsonAsync<AccessTokenResponse>();

                if (accesstoken.errcode == EnumErrorCode.Success)
                {
                    return accesstoken.access_token;
                }
                else
                {
                    Console.WriteLine("获取微信AccessToken失败！");
                    return null;
                }
            }
            catch (Exception ex)
            {
                var error = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}>>>>获取微信AccessToken异常>>>>>{ex.Message}";
                _logger.Error(error);
                Console.WriteLine(error);
                return null;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete"), TypeFilter(typeof(ActionFilter))]
        public async Task<ApiResult<string>> Delete([FromBody] List<string> ids)
        {
            var res = await _sysPlatformRepository.Delete(ids);
            if (res > 0)
            {
                return new ApiResult<string>() { Success = true, StatusCode = StatusCodeEnum.OK, Msg = "删除成功" };
            }
            return new ApiResult<string>() { Success = true, StatusCode = StatusCodeEnum.Error, Msg = "删除失败" };
        }

        /// <summary>
        /// 根据ID主键获取详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("get"), TypeFilter(typeof(ActionFilter))]
        public async Task<ApiResult<SysPlatformEntity>> Get([FromQuery] string id)
        {
            var res = await _sysPlatformRepository.Get(id);
            if (res != null)
            {
                return new ApiResult<SysPlatformEntity>() { Success = true, StatusCode = StatusCodeEnum.OK, Data = res };
            }
            return new ApiResult<SysPlatformEntity>() { Success = true, StatusCode = StatusCodeEnum.NotFound };
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPut("update"), TypeFilter(typeof(ActionFilter))]
        public async Task<ApiResult<string>> UpdateDcAppUser([FromBody] SysPlatformEntity entity)
        {
            entity.UpdateTime = DateTime.Now;
            var res = await _sysPlatformRepository.Update(entity);
            if (res > 0)
            {
                return new ApiResult<string>() { Success = true, StatusCode = StatusCodeEnum.OK, Msg = "修改成功" };
            }
            return new ApiResult<string>() { Success = true, StatusCode = StatusCodeEnum.Error, Msg = "修改失败" };
        }
    }
}
